﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace nanoCMS.Core.WebProviders {
	public class StopwatchActionFilter : ActionFilterAttribute
	{
		private readonly Dictionary<string, Stopwatch> _stopWatches;

		public StopwatchActionFilter()
		{
			if (_stopWatches == null)
				_stopWatches = new Dictionary<string, Stopwatch>();
		}

		public override void OnActionExecuting(ActionExecutingContext filterContext) {
			string actionName = filterContext.RequestContext.RouteData.Values["Action"].ToString();
			string controllerName = filterContext.RequestContext.RouteData.Values["Controller"].ToString();

			string key = String.Format("NC-{0}-{1}", controllerName, actionName);
			if (_stopWatches.ContainsKey(key))
				_stopWatches[key].Reset();
			else
				_stopWatches.Add(key, new Stopwatch());
			_stopWatches[key].Start();
			base.OnActionExecuting(filterContext);
		}

		public override void OnActionExecuted(ActionExecutedContext filterContext) {
			string actionName = filterContext.RequestContext.RouteData.Values["Action"].ToString();
			string controllerName = filterContext.RequestContext.RouteData.Values["Controller"].ToString();

			string key = String.Format("NC-{0}-{1}", controllerName, actionName);
			_stopWatches[key].Stop();
			filterContext.HttpContext.Response.AddHeader(key , _stopWatches[key].ElapsedMilliseconds.ToString() + "ms");
			base.OnActionExecuted(filterContext);
		}

	}
}
